package com.course02.order_backend.controller.LXY;


import cn.hutool.json.JSONUtil;
import com.course02.order_backend.dto.LXY.Result;
import com.course02.order_backend.security.LXY.LoginUserDetails;
import com.course02.order_backend.utils.LXY.JwtUtils;
import com.course02.order_backend.utils.LXY.RedisUtils;
import io.netty.util.internal.StringUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author wozhe
 */
@RestController
public class LoginController {
    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisUtils redisUtils;
    /**
     * 登录
     * @param phone 手机号
     * @param password 密码
     * @return 响应结果
     */
    @PostMapping(value = "/login")
    public Result login(String phone, String password, HttpServletRequest request){
        //判断曾经登录是否还在有效期
        String oldToken=request.getHeader("token");
        //判断token是否存在
        if(StringUtils.hasText(oldToken)){
            String claim=JwtUtils.getClaim(oldToken);
            if(StringUtils.hasText(claim) && claim.equals(phone)){
                //存在，那就删除,防止生成多个token
                String key="login:token:"+oldToken;
                redisUtils.del(key);
            }
        }
        /*
          封装用户名和密码
         */
        UsernamePasswordAuthenticationToken authenticationToken  = new UsernamePasswordAuthenticationToken(phone, password);

        /*
          调用认证方法
          Authentication：如果成功，封装了用户的信息包括账号密码和权限
         */
        try{
            Authentication authenticate = authenticationManager.authenticate(authenticationToken );
            if(Objects.isNull(authenticate)){
                return Result.error("用户名或者密码错误");
            }

            //生成Token,时间设置未两天
            String token= JwtUtils.sign(phone,1000*60*60*24*2L);
            //保存Token到Redis中,用login:token中间加冒号分层
            String key="login:token:"+token;
            //将用户信息json化
            LoginUserDetails principal = (LoginUserDetails) authenticate.getPrincipal();
            String json= JSONUtil.toJsonStr(principal);
            redisUtils.set(key,json,1000*60*60*24*2L);
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            return Result.ok(map);

        }catch (Exception e){
            e.printStackTrace();
            return Result.error("用户名或者密码错误");
        }
    }
}
